import importlib
import inspect
import sys
import os

from .command import Command

class Commander:

    def __init__(self):
        self.commands = list()
        self.extension = ".py"
        self.path = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
        self.init_commands()

    def init_commands(self):
        for file in os.listdir(self.path):
            if file.endswith(self.extension):
                file = file[:-3]
                if file == "core": continue

                name = f"..{file}"
                cfile = importlib.import_module(name=name, package=f'commands.{file}')

                for it in dir(cfile):
                    obj = getattr(cfile, it)

                    if inspect.isclass(obj) and issubclass(obj, Command) and obj != Command:
                        command = obj()
                        self.commands.append(command)

    def print_commands(self):
        for command in self.commands:
            print(command.name)

    def execute_command(self, command: str, obj):
        cmd_list = command.split(" ")
        name = cmd_list[0]
        args = cmd_list[1:]
        for cmd in self.commands:
            if name in cmd.names:
                return cmd.execute(args, obj)
        return f"Error: Command {command} not found!"

if __name__ == "__main__":
    cm = Commander()
    cm.print_commands()


